package xuyuanjun.paymenthandler;

import xuyuanjun.paymenthandler.context.AccountsContext;
import xuyuanjun.paymenthandler.entities.Transaction;

import java.io.*;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Hello world!
 *
 */
public class App 
{	
    public static void main(String[] args)
    {    	    
    	AccountsContext context = AccountsContext.getInstance();
    	System.out.println("123");
		System.out.println("abc");
    	//read transactions from given files
    	for (String fileName : args) {
    		File f = new File(fileName);    
    		BufferedReader br = null;
    		try {
    			br = new BufferedReader(new FileReader(f));
				String tmpLine = null;
				while ((tmpLine = br.readLine()) != null) {
					String[] strs = tmpLine.split(" ");
					double amount;
					try {
						amount = Double.parseDouble(strs[1]);
						context.processTransaction(new Transaction(strs[0], amount));
					} catch (Exception e) {
						System.out.println("Warning: the file input format is invalid: " + tmpLine);
					}
				}
				br.close();
			} catch (FileNotFoundException e) {
				System.out.println("Warning: the file(" + fileName + ") does not exist.");
			} catch (IOException e) {
				e.printStackTrace();				
			} finally {
				if (br != null) {
					try {
						br.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
    	}
    	
    	//create scheduled task to output accounts info(once per minute)
    	ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1);
    	scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
			
			public void run() {				
				AccountsContext context = AccountsContext.getInstance();
				System.out.println("Scheduled task output status of each accounts:");
				context.outputAllAccountsBalance();
			}
			
		}, 60, 60, TimeUnit.SECONDS);
    	
    	//read console input
    	Scanner scanner = new Scanner(System.in);
    	while (scanner.hasNext()) {
    		String command1 = scanner.next();
    		if (command1.toLowerCase().equals("quit")) {
    			break;
    		}
    		String amountStr = scanner.next();
    		double amount;
    		try {
				amount = Double.parseDouble(amountStr);
				context.processTransaction(new Transaction(command1, amount));
			} catch (Exception e) {
				System.out.println("Warning: the input format is invalid(must be CURRENCY_CODE AMOUNT)");
			}
    	}
    	
    	scheduledThreadPool.shutdownNow();
    	System.out.println("Application Existing...");
    	System.out.println("The final status of each accounts:");
    	context.outputAllAccountsBalance();
    }
}
